package cz.mzk.funnylib.api;

/*
 * Copyright (C) 2012 Martin Řehánek
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import cz.mzk.funnylib.api.builders.BookChecksBuilder;
import cz.mzk.funnylib.api.builders.LibrariesBuilder;
import cz.mzk.funnylib.api.builders.LibraryBuilder;
import cz.mzk.funnylib.api.builders.LibraryChecksBuilder;
import cz.mzk.funnylib.api.builders.UserBuilder;
import cz.mzk.funnylib.api.builders.UsersBuilder;
import cz.mzk.funnylib.dao.BookCheckDAO;
import cz.mzk.funnylib.dao.LibraryCheckDAO;
import cz.mzk.funnylib.dao.UserDAO;
import cz.mzk.funnylib.dao.db.BookCheckDAOImpl;
import cz.mzk.funnylib.dao.db.LibraryCheckDAOImpl;
import cz.mzk.funnylib.dao.db.UserDAOImpl;
import cz.mzk.funnylib.entities.BookCheck;
import cz.mzk.funnylib.entities.LibraryCheck;
import cz.mzk.funnylib.entities.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Martin Řehánek
 */
@WebServlet(name = "Api", urlPatterns = {"/Api"})
public class Api extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");

            //create
            if (action.equals("createUser")) {
                createUser(request);
            } else if (action.equals("createBookCheck")) {
                createBookCheck(request);
            } else if (action.equals("createLibraryCheck")) {
                createLibraryCheck(request);
            } //read
            else if (action.equals("getLibraries")) {
                LibrariesBuilder builder = new LibrariesBuilder();
                out.print(builder.buildLibraries());
            } else if (action.equals("getLibrary")) {
                Long id = Long.valueOf(request.getParameter("id"));
                out.print((new LibraryBuilder()).buildLibrary(id));
            } else if (action.equals("getUsers")) {
                UsersBuilder builder = new UsersBuilder();
                out.print(builder.buildUsers());
            } else if (action.equals("getUser")) {
                String idString = request.getParameter("id");
                String login = request.getParameter("login");
                if (idString != null) {
                    Long id = Long.valueOf(request.getParameter("id"));
                    out.print(new UserBuilder().buildUserById(id));
                } else if (login != null) {
                    out.print(new UserBuilder().buildUserByLogin(login));
                }
            } else if (action.equals("getLibraryChecks")) {
                Long userId = Long.valueOf(request.getParameter("userId"));
                out.print(new LibraryChecksBuilder().buildLibraryChecksOfUser(userId));
            } else if (action.equals("getBookChecks")) {
                Long userId = Long.valueOf(request.getParameter("userId"));
                out.print(new BookChecksBuilder().buildBookChecksOfUser(userId));
            } else if (action.equals("findTitle")) {
                String isbn = request.getParameter("isbn");
                GoogleBooksSearcher searcher = new GoogleBooksSearcher();
                String title = searcher.searchTitleByIsbn(isbn);
                out.print(title);
            } else {
                out.println("unknown action: " + action);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void createUser(HttpServletRequest request) {
        String name = request.getParameter("name");
        String surname = request.getParameter("surname");
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        User user = new User();
        user.setName(name);
        user.setSurname(surname);
        user.setLogin(login);
        user.setPassword(password);
        UserDAO dao = new UserDAOImpl(Configuration.getTemplate());
        dao.persist(user);
    }

    private void createBookCheck(HttpServletRequest request) {
        Long userId = Long.valueOf(request.getParameter("userId"));
        Long libraryId = Long.valueOf(request.getParameter("libraryId"));
        String name = request.getParameter("name");
        String isbn = request.getParameter("isbn");
        Date date = new Date();
        BookCheck check = new BookCheck();
        check.setUserId(userId);
        check.setLibraryId(libraryId);
        check.setName(name);
        check.setIsbn(isbn);
        check.setDate(date);
        BookCheckDAO dao = new BookCheckDAOImpl(Configuration.getTemplate());
        dao.persist(check);
    }

    private void createLibraryCheck(HttpServletRequest request) {
        Long userId = Long.valueOf(request.getParameter("userId"));
        Long libraryId = Long.valueOf(request.getParameter("libraryId"));
        Date date = new Date();
        LibraryCheck check = new LibraryCheck();
        check.setUserId(userId);
        check.setLibraryId(libraryId);
        check.setDate(date);
        LibraryCheckDAO dao = new LibraryCheckDAOImpl(Configuration.getTemplate());
        dao.persist(check);
    }
}
